<?php
interface Flyweight
{
    public function operate($x);
}

class ConcreteFlyweight implements Flyweight
{
    /** @var string $type type作为内部状态，type相同的对象可以共用一个享元 */
    public $type="";
    /** @var string $id 随机的，用来判断是否是同一个对象 */
    private $id;
    public function __construct($type)
    {
        $this->id=rand(100000,999999);
        $this->type=$type;
    }
    /** @var string $x x作为外部状态，x不同的对象也可以共用一个享元 */
    public function operate($x)
    {
        echo "({$this->id})type:{$this->type},x:{$x}\r\n";
    }
}

class FlyweightFactory
{
    /** @var Flyweight[] $map */
    public $map=[];
    /** @return Flyweight */
    public function getFlyweight($type)
    {
        if(!isset($this->map[$type])){
            $this->map[$type] = new ConcreteFlyweight($type);
        }
        return $this->map[$type];
    }
}

header('Content-Type: text/plain');

$factory = new FlyweightFactory;
$factory->getFlyweight("rth")->operate("1564645");
$factory->getFlyweight("thre")->operate("74586598");
$factory->getFlyweight("mmmc")->operate("2452454");
$factory->getFlyweight("bgf")->operate("75682658");
$factory->getFlyweight("mmmc")->operate("562456");
$factory->getFlyweight("rth")->operate("54265");
$factory->getFlyweight("bgf")->operate("5462456");
$factory->getFlyweight("thre")->operate("4562546");
$factory->getFlyweight("threrh")->operate("546");
$factory->getFlyweight("mmmc")->operate("426546");
$factory->getFlyweight("rtht")->operate("5472547");
$factory->getFlyweight("threrh")->operate("65426546");

echo "共创建". count($factory->map) ."个对象";
